<template>
  <div class="wrapper">
    <div class="form">
      <div class="avatar">
        <div style="line-height: 125px">
          <span>个人头像</span>
        </div>
        <div style="margin-left: 70px">
          <el-image :src="avatar"
                    style="width: 120px;height: 120px; border-radius: 50%"
                    @click="avatarUpload"
          >
          </el-image>
          <input type="file" accept="image/*" class="avatarUpload" v-show="false" @change="setImage"></input>
        </div>
      </div>
      <div class="info">
        <el-form label-position="left" label-width="90px" :model="currentUser">
          <el-form-item label="用户名">
            <el-input disabled v-model="currentUser.account"></el-input>
          </el-form-item>
          <el-form-item label="昵 称">
            <el-input v-model="currentUser.nick"></el-input>
          </el-form-item>
          <el-form-item label="个人签名">
            <el-input v-model="currentUser.signature"></el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="currentUser.phone"></el-input>
          </el-form-item>
          <el-form-item label="密 码">
            <el-button type="danger" :disabled="resetPassword" @click="resetPassword=true">重置密码</el-button>
            <span v-show="resetPassword">密码已重置！保存后生效！</span>
          </el-form-item>
        </el-form>
        <div style="text-align: center">
          <el-button @click="reset">撤销</el-button>
          <el-button type="success" @click="saveEdit">保存</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
    export default {
        name: "AccountInfo",
        data() {
            return {
                currentUser: {},
                noAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
                resetPassword: false,
                file: null,
                uploadImgUrl: '',
                oldImgUrl: ''
            }
        },
        mounted() {
           this.reset();
        },
        computed: {
            avatar() {
                if(this.file){
                    return this.uploadImgUrl;
                }
                return this.currentUser.avatarUrl ? '/api/' + this.currentUser.avatarUrl : this.noAvatar;
            }
        },
        methods: {
            reset(){
                const user = sessionStorage.getItem("currentUser");
                this.currentUser = JSON.parse(user);
                this.file=null;
                this.resetPassword=false;
                this.oldImgUrl=this.currentUser.avatarUrl;
            },
            // 保存编辑
            saveEdit() {
                this.$confirm('确定保存对您信息的更改吗？',
                    '警告', { type: 'warning' }).then(async () => {
                    const date=new Date();
                    this.currentUser.updateBy=this.currentUser.userId;
                    this.currentUser.updateTime=this.datetime2string(date);
                    const res= await this.syncRequest();
                    if(res && res.data!==''){
                        this.currentUser.avatarUrl=res.data;
                    }
                    const params = { user: this.currentUser, resetPassword: this.resetPassword};
                    this.postRequest('/updateUser', params).then(resp => {
                        this.currentUser.avatarUrl=res ? this.uploadImgUrl : this.oldImgUrl;
                        if (resp === 'success') {
                            this.resetPassword= false;
                            this.$message.success('保存成功！重新登录后生效！');
                        } else {
                            this.$message.error('操作失败！');
                        }
                    });
                }).catch(() => {
                });
            },
            avatarUpload() {
                document.querySelector('.avatarUpload').click();
            },
            setImage(e) {
                const file = e.target.files[0];
                this.file = file;
                if (!file.type.includes('image/')) {
                    this.$message.error('请选择图片文件');
                    return;
                }
                const reader = new FileReader();
                reader.onload = (event) => {
                    this.currentUser.avatarUrl = event.target.result;
                    this.uploadImgUrl=event.target.result;
                    e.target.value = '';
                };
                reader.readAsDataURL(file);
            },
            async syncRequest(){  //同步请求方法，axios默认是异步请求，同步需要使用async和await关键字
                let formData=new FormData();
                formData.append('img', this.file);
                if(this.file===null){
                    return null;
                }
                let res=await this.$axios({
                    method: 'post',
                    url: '/api/saveImageToServer',
                    data: formData
                });
                return res;
            }
        }
    }
</script>

<style scoped>
  .wrapper {
    width: 60%;
    background-color: white;
    padding: 30px 20px;
    margin: 10px auto;
    border: 1px solid #eaeaea;
    box-shadow: 0 0 25px #cac6c6;
  }

  .avatar {
    display: flex;
    flex-direction: row;
  }

  .info {
    margin-top: 20px;
  }
  .form{
    width: 60%;
    margin: 0 auto;
  }

  .el-form-item span {
    margin-left: 10px;
    font-size: 10px;
    color: red;
  }
</style>
